<template>
	<!-- currentindex 刚开始 =0 那么 会让 打开页面 如果一开始 不是第一张 会产生滑动效果 -->
	<!-- 可以加v-if 当 picInfoObj被赋值之后 再渲染 -->
	<view class="preview" v-if="picInfoObj._id">
		<swiper @change="swiperChange" :current="currentIndex" circular>
			<swiper-item v-for="(item,index) in classList" :key="item._id">
				<!-- v-if 控制 首张图加载速度 -->
				<image v-if="imageList.includes(index)" @click="maskChange" :src="item.picurl" mode="aspectFill"></image>

			</swiper-item>

		</swiper>
		<!-- <view>{{imageList}}</view> -->
		<view class="mask" v-if="showBox">
			<view class="goBack" :style="{top:statusBarHeight()+'px'}"  @click="goBack">
				<uni-icons type="back" color="#fff" size="20"></uni-icons>
			</view>
			<view class="count">{{currentIndex+1}}/{{classList.length}}</view>
			<view class="time">
				<uni-dateformat :date="new Date()" format="hh:mm"></uni-dateformat>
			</view>
			<view class="date">
				<uni-dateformat :date="new Date()" format="MM月dd日"></uni-dateformat>
			</view>
			<view class="footer">
				<view class="box" @click="clickInfo">
					<uni-icons type="info" size="23"></uni-icons>
					<view class="text">信息</view>
				</view>
				<view class="box" @click="clickScore">
					<uni-icons type="star" size="23"></uni-icons>
					<view class="text">{{picInfoObj.score}}分</view>
				</view>
				<view class="box" @click="clickDownload">
					<uni-icons type="download" size="23"></uni-icons>
					<view class="text">下载</view>
				</view>
			</view>


		</view>

<!-- safe-area false 控制 弹窗底部不留 空 -->

		<uni-popup ref="infoPopup" :safe-area="false">
			<view class="infoPopup">
				<view class="popHeader">
					<view></view>
					<view class="title">壁纸信息</view>
					<view class="close" @click="closePopup">
						<uni-icons type="closeempty" size="18" color="#999">
						</uni-icons>
					</view>

				</view>
				<scroll-view scroll-y="true">
					<view class="content">
						<view class="row">
							<view class="label">壁纸ID ：</view>
							<text class='value'>{{picInfoObj._id}}</text>
						</view>
						<view class="row">
							<view class="label">分类 ：</view>
							<text class='value classify'>{{picInfoObj.tabs?.join('/')}}</text>
						</view>
						<view class="row">
							<view class="label">发布者 ：</view>
							<text class='value'>{{picInfoObj.nickname}}</text>
						</view>
						<view class="row">
							<view class="label">评分 ：</view>
							<view class='value rateBox'>
								<uni-rate v-model="picInfoObj.score" @change="onChange" readonly size="16" />
								<text class="score">{{picInfoObj.score}}分</text>
							</view>
						</view>
						<view class="row">
							<view class="label">摘要 ：</view>
							<text class='value'>{{picInfoObj.description}}</text>
						</view>
						<view class="row">
							<view class="label">标签 ：</view>
							<view class='value  tabs'>
								<view v-for="(i,index) in picInfoObj.tabs" class="tab" :key="index">{{i}}</view>

							</view>
						</view>
						<view class="copyright row">
							本站版权属于xxx(xx)信息科技有限公司所有,未经xxx(xx)信息科技有限公司书面授权,任何企业、网站、个人不得转载、摘编、镜像或利用其它方式使用本站内容。
						</view>
					</view>
				</scroll-view>
			</view>

		</uni-popup>
		<uni-popup ref="scorePopup">
			<view class="scorePopup">
				<view class="popHeader">
					<view></view>
					<view class="title">{{isScore?'评分过了~':'壁纸评分'}}</view>
					<view class="close" @click="closeScorePopup">
						<uni-icons type="closeempty" size="18" color="#999">
						</uni-icons>
					</view>

				</view>
				<view class="content">
					<uni-rate v-model="userScore" @change="onChange" allowHalf  :disabled="isScore?true:false" disabled-color="#FFCA3E"></uni-rate>
					<text class="score">{{userScore}}分</text>
					
				</view>
				<view class="footer">
					 <!-- 如果 评价过了 禁用按钮，如果 给0分 也不能提交 -->
					<button type="default" size="mini" @click="submitScore" :disabled="!userScore || isScore">确认评分</button>
					
				</view>
			</view>
		</uni-popup>
	</view>
</template>
<script setup>
import {statusBarHeight,getTitleBarHeight,getNavBarHeight} from '@/utils/system.js';
import {apiGetPicInfo,apiChangeScore,apiGetDownload} from "@/api/api.js"
// 已经评过分 的不再评分
const isScore = ref(false);
	const infoPopup = ref(null)
	const showBox = ref(false)
	const userScore = ref(0)
	const scorePopup = ref(null)
	const  storageClassList=ref([])
	storageClassList.value=uni.getStorageSync("storageClassList")||[]
	console.log('123',storageClassList.value)
	const classList=ref([])
	const currentIndex=ref(0)
	const cid=ref("")
	const picInfoObj=ref({})
	const imageList=ref([])
	
	// watch(showBox,(val)=>{
	// 	if(val){
	// 		getPicInfo()
	// 	}
		
	// })
	classList.value=storageClassList.value.map(item=>{
		console.log('in')
		console.log('item',item)
		return {
			...item,
			picurl:item.smallPicurl.replace("_small.webp",".jpg")
		}
	})
	console.log('big',classList.value)
	
	onShareAppMessage((res)=>{
		console.log('share',res)
		// 右上角 悬浮 是 from menu
		// 还有 一种 button opentype share
		return {
			title:"wallpaper123",
			// 如果分享首页 就写首页地址
			// path:`/pages/classlist/classlist?classid=${queryParams.value.classid}&name=${name.value}}`
			path:`/pages/preview/preview?id=${cid.value}&type=share`
		}
		
	})
	// onShareTimeline(()=>{
	// 	// 分享需要在微信认证之后
	// 	return {
	// 		title:"wallpaperpyq",
	// 		// 如果分享首页 就写首页地址
	// 		path:"/pages/index/index",
	// 		// 如果用了common里的 要引入，这里演示 用static
	// 		imageUrl:bannerList.value[0].picurl
	// 	}
	// })
	
	onLoad(async(option)=>{
		//如果 是  分享朋友 来的 ，就只有一张图片 type=share
		if(option.type==='share'){
			
			let res=await apiGetPicInfo({id:option.id});
			classList.value=res.data.map(
			item=>{
				console.log('in')
				console.log('item',item)
				return {
					...item,
					picurl:item.smallPicurl.replace("_small.webp",".jpg")
				}
			})
			
			
		}
		console.log('storageClassList.value.map(i=>i._id)',storageClassList.value.map(i=>i._id))
		console.log('option.id',option.id)
		cid.value=option.id;
		currentIndex.value=classList.value.map(i=>i._id).indexOf(cid.value+'')
		console.log('currentIndex',currentIndex)
		picInfoObj.value=classList.value[currentIndex.value]
	
		getNeibor(currentIndex.value)
	})
	const clickDownload=async()=>{
		// uni.previewImage({
		//   urls: classList.value.map(i=>i.picurl), //需要预览的图片http链接列表，多张的时候，url直接写在后面就行了
		//   current: currentIndex.value, // 当前显示图片的http链接，默认是第一个
		//   success: function (res) {},
		//   fail: function (res) {},
		//   complete: function (res) {},
		// });
		// #ifdef H5
		uni.showModal({
			content:"长按保存壁纸",
			showCancel:false
		})
		// #endif
		
		// #ifndef H5
		// 小程序 要下载 网络图片必须配置白名单
		try{
			uni.showLoading({
				title:'下载中...',
				mask:true
			})
			// 请求下载接口，做好 下载记录
			let res=await apiGetDownload({
				classid:picInfoObj.value.classid,
				wallId:picInfoObj.value._id
			})
			// 以下只是  200 请求成功返回的，如果要捕获 request 400的错误要在外面catch
			if(res.errCode!=0) throw res;
			console.log('download',res)
			
			uni.getImageInfo({
				src:picInfoObj.value.picurl,
				success:(res)=>{
					console.log('wangl',res)
					// 根据src网络地址 获取图片本地地址，相当于下载 
					uni.saveImageToPhotosAlbum({
						filePath:res.path,
						success:(res)=>{
							console.log('save right',res)
						},
						fail:err=>{
						
							// 这个 err 用户秒如果已经授权 但是没点击保存图片 点了取消 {errMsg: "saveImageToPhotosAlbum:fail cancel"}
							//  以上情况不该再次 调出授权 请求 对话框
							console.log('err 用户秒如果没点击保存 点了取消',err)
							// 如果  用户点击了拒绝存入 相册， 这里再次调出对话框 ，询问授权
					if(err.errMsg==='saveImageToPhotosAlbum:fail cancel'){
						uni.showToast({
							title:'保存失败，请重新点击下载',
							icon:"none"
						})
						// 用户选择不保存 就 不再调出  再次询问框
						return;
					}
							uni.showModal({
								title:'授权提示',
								content:"需要授权保存相册",
								success:res=>{
									if(res.confirm){
										console.log('reagree')
										uni.openSetting(
										{
										  success(setting) {
											  // res.authSetting.scope.writePhotosAlbum: true 就是同意
										    console.log('setting',setting.authSetting['scope.writePhotosAlbum'])
											if(setting.authSetting['scope.writePhotosAlbum']){
												uni.showModal({
													title:"获取授权成功",
													icon:"none"
												})
											}else{
												uni.showModal({
													title:"获取授权失败",
													icon:"none"
												})
												
											}
										  }
										})
									}
								}
							})
							
						},
						complete:()=> {
							uni.hideLoading()
						}
						
					})
				}
			})
			
		}catch(err){
			console.log('request报错 下载过于频繁',err)
			uni.hideLoading()
		}

		// #endif
		
		
	}
	const getNeibor=(index)=>{
		let res=[index<1?classList.value.length-1:index-1,index,index>classList.value.length-2?0:index+1];
		console.log('reslist',res)
		imageList.value.push(...res)
		imageList.value=[...new Set(imageList.value)]
		
	}
	const swiperChange=(e)=>{
		console.log('e.detail',e.detail)
		currentIndex.value=e.detail.current;
		cid.value=classList.value[currentIndex.value]._id
		picInfoObj.value=classList.value[currentIndex.value]
		getNeibor(currentIndex.value)
	}
	const goBack=()=>{
		uni.navigateBack({
			success:()=>{},
			//如果是从 朋友圈 或者分享给好友 进来的，没有 上一个页面就直接 回首页
			fail:(err)=>{
				uni.reLaunch({
					url:'/pages/index/index'
				})
			}
		})
	}
	const onChange = (e) => {
		console.log('rate发生改变:' + JSON.stringify(e))
	}

	const maskChange = () => {
		showBox.value = !showBox.value

	}
	const clickInfo = () => {
		infoPopup.value.open('bottom')
		// getPicInfo();

	}
	
	const getPicInfo=async()=>{
		let res=await apiGetPicInfo({id:cid.value});
		console.log('pic',res.data[0])
		picInfoObj.value={...res.data[0]}
	}
	const closePopup = () => {
		infoPopup.value.close()
	}
	const closeScorePopup=()=>{
				userScore.value = 0;
				isScore.value = false;

		scorePopup.value.close()
	}
	// 点击弹出评分弹窗
	const clickScore = () => {
		
	if(picInfoObj.value.userScore){
		isScore.value = true;
		userScore.value = picInfoObj.value.userScore;
	}
		scorePopup.value.open('center')
	}
	// 提交评分
	const submitScore=async()=>{
		uni.showLoading({
			title:"加载中..."
		})
		console.log('userScore',userScore.value)
		let params= {
			classid:picInfoObj.value.classid,
			wallId:picInfoObj.value._id,
			userScore:userScore.value
			
		};
		let res=await apiChangeScore(params)
		uni.hideLoading();
		if(res.errCode===0){
			uni.showToast({
				title:'评分成功',
				icon:"none"
			})
		classList.value[currentIndex.value].userScore=userScore.value
					 uni.setStorageSync("storageClassList",classList.value)
		
		
		closeScorePopup();
		
		}
	}

	// export default {
	// 	data() {
	// 		return {

	// 		}
	// 	},
	// 	methods: {

	// 	}
	// }
</script>

<style lang="scss" scoped>
	.preview {
		width: 100%;
		height: 100vh;
		position: relative;

		// 用了 100vh 就熬 navigatebar custom 不然高度 会超出
		swiper {
			width: 100%;
			height: 100%;

			image {
				width: 100%;
				height: 100%;
			}
		}

		.mask {
			&>view {
				position: absolute;
				left: 0;
				right: 0;
				// 根据内容定宽度
				margin: auto;
				color: #fff;
				width: fit-content;

			}

			.goBack {
				height:38px;
				width:38px;
				background:rgba(0,0,0,0.5);
				left:30rpx;
				margin-left:0;
				border-radius:100px;
				top:0;
				backdrop-filter:blur(10rpx);
				border:1rpx solid rgba(255,255,255,0.3);
				display:flex;
				justify-content: center;
				align-items: center;
			}

			.count {

				top: 10vh;


				background: rgba(0, 0, 0, 0.3);

				font-size: 28rpx;
				border-radius: 40rpx;
				padding: 8rpx 28rpx;
				backdrop-filter: blur(10rpx);


			}

			.time {

				top: calc(10vh + 80rpx);



				font-size: 140rpx;
				font-weight: 100rpx;
				line-height: 1em;
				text-shadow: 0 4rpx rgba(0, 0, 0, 0.3);


			}

			.date {
				top: calc(10vh + 230rpx);



				font-size: 34rpx;
				font-weight: 100rpx;

				text-shadow: 0 2rpx rgba(0, 0, 0, 0.3);

			}

			.footer {
				background: rgba(255, 255, 255, 0.8);
				bottom: 10vh;
				width: 65vw;
				height: 120rpx;
				display: flex;
				border-radius: 65rpx;
				justify-content: space-around;
				align-items: center;
				box-shadow: 0 2rpx 0 rgba(0, 0, 0, 0.1);
				backdrop-filter: blur(20rpx);

				.box {
					display: flex;
					flex-direction: column;
					align-items: center;
					justify-content: center;
					padding: 2rpx 12rpx;

					.text {
						font-size: 26rpx;
						color: $text-font-color-2;
					}
				}

			}
		}



		.infoPopup {
			background: #fff;
			padding: 30rpx;
			border-radius: 30rpx 30rpx 0 0;
			overflow: hidden;

			.popHeader {
				display: flex;
				justify-content: space-between;
				align-items: center;

				// margin-bottom:10vh;
				.title {
					color: $text-font-color-2;
				}

				.close {
					// border:1rpx solid red;
					padding: 6rpx;
				}
			}

			scroll-view {
				max-height: 60vh;

				.content {
					.row {
						display: flex;
						padding: 16rpx 0;
						font-size: 32rpx;
						line-height: 1.7em;
						display: flex;

						.label {
							color: $text-font-color-3;
							width: 140rpx;
							text-align: right;
							font-size: 30rpx;

						}

						.value {
							flex: 1;
							width: 0;
						}

						.classify {
							color: $brand-theme-color;
						}

						.rateBox {
							display: flex;
							align-items: center;

							.score {
								font-size: 26rpx;
								color: $text-font-color-2;
								padding-left: 10rpx;
								color:rgb(255, 202, 62);

							}

						}

						.tabs {
							display: flex;
							flex-wrap: wrap;

							.tab {
								border: 1px solid $brand-theme-color;
								color: $brand-theme-color;
								font-size: 22rpx;
								padding: 10rpx 30rpx;
								border-radius: 40rpx;
								line-height: 1em;
								margin: 0 10rpx 10rpx 0;
							}

						}


					}




					.copyright {
						font-size: 28rpx;
						padding: 20rpx;
						background: #f6f6f6;
						color: #666;
						border-radius: 10rpx;
						margin: 20rpx 0;
						line-height: 1.6em;

					}
				}


			}
		}
	
	
	
	.scorePopup{
		background: #fff;
		padding: 30rpx;
		width:70vw;
		border-radius: 30rpx 30rpx 30rpx 30rpx;
		overflow: hidden;
		
		.popHeader {
			display: flex;
			justify-content: space-between;
			align-items: center;
		
			// margin-bottom:10vh;
			.title {
				color: $text-font-color-2;
			}
		
			.close {
				// border:1rpx solid red;
				padding: 6rpx;
			}
		}
		
	
	
	.content{
		color:rgb(255, 202, 62);
		display:flex;
		padding:30rpx 0;
		justify-content: center;
		align-items: center;
		.score{
				padding-left: 10rpx;
				width:80rpx;
				line-height:1em;
				
		}
		
	}
	.footer{
		
		margin:auto;
		text-align:center;
		
	}
	}
	
	}
</style>